import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { subNumber } from "../store/features/counter";
import { changeBanners, changeRecommends, fetchHomeMultidataAction } from '../store/features/home';
import axios from 'axios'

class Home extends PureComponent {

  componentDidMount() {
    //方式1：在组件中进行异步网络请求，将数据存储到store
    // axios.get("http://123.207.32.32:8000/home/multidata").then(res => {
    //   const banners = res.data.data.banner.list;
    //   const recommends = res.data.data.recommend.list;
    //   // console.log(banners);
    //   // console.log(recommends);
    //   this.props.changeBanners(banners);
    //   this.props.changeRecommends(recommends)
    // })

    //方式2：使用reducer中写好的异步网络请求方法
    this.props.fetchHomeMultidata();
  }
  
  subNumber(num) {
    this.props.subNumber(num);
  }

  render() { 
    const { counter, banners, recommends } = this.props
    return ( 
      <div>
        <h2>Home Counter: {counter}</h2>
        <button onClick={() => this.subNumber(5)}>-5</button>
        <button onClick={() => this.subNumber(8)}>-8</button>
        <div className='banner'>
          <h2>轮播图展示：</h2>
          <ul>
            {
              banners.map((item, index) => {
                return <li key={index}>{item.title}</li>
              })
            }
          </ul>
        </div>
        <div className='recommend'>
          <h2>推荐数据展示：</h2>
          <ul>
            {
              recommends.map((item, index) => {
                return <li key={index}>{item.title}</li>
              })
            }
          </ul>
        </div>
      </div>
     );
  }
}

const mapStateToProps = (state, ownProps) => ({
  counter: state.counter.counter,
  banners: state.home.banners,
  recommends: state.home.recommends
})

const mapDispatchToProps = (dispatch, ownProps) => ({
  subNumber: (num) => {
    dispatch(subNumber(num))
  },
  // changeBanners(banners) {
  //   dispatch(changeBanners(banners))
  // },
  // changeRecommends(recommends) {
  //   dispatch(changeRecommends(recommends))
  // },

  //方式2：将发送网络请求的方法封装到reducer中，直接dispatch
  fetchHomeMultidata() {
    dispatch(fetchHomeMultidataAction())
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(Home);